from flask import render_template, redirect, url_for, request, jsonify, abort
from flask_login import login_user, current_user, logout_user, login_required
from .models import U, T
from config import db
from werkzeug.security import generate_password_hash
from pprint import pprint
import json
from datetime import datetime, timedelta
import utils
import random


# 装饰器需要用户强制登录
@login_required
def index():
    user_data = current_user

    if user_data.img_path:
        user_data.Storage_path = user_data.img_path[7:]
    else:
        user_data.Storage_path = '/static/img/touxiang.jpg'

    Tweet_sql = user_data.popular_and_followed_Tweets()
    Tweet_data = user_data.popular_and_followed_Tweets().all()

    for index, value in enumerate(Tweet_data):
        # pprint(Tweet_list[index].id)
        Tweet_data[index].hot = ""
        for i in range(5):
            if index == i:
                Tweet_data[index].hot = "热门推荐"

        datas = utils.Capture_image_path(value.body)
        if datas:
            Tweet_data[index].cover = datas[0]
        else:
            Tweet_data[index].cover = "static/img/jzytp.jpg"

    # 分页start
    limit = 10
    page = request.args.get("page", 1, type=int)
    start = (page - 1) * limit
    end = page * limit if len(Tweet_data) > page * limit else len(Tweet_data)
    paginate = Tweet_sql.paginate(page=page, per_page=limit, error_out=False)
    ret = Tweet_sql.slice(start, end)
    # 分页end

    # 受欢迎的10条数据
    popular_ten_datas = T.popular_ten_data()

    return render_template('index.html', user_data=user_data, T_data=ret, paginate=paginate,
                           popular_ten_data=popular_ten_datas)


# 登录
def login():
    # 如果已经登录的话(判断是否已经登录)
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    next_page = request.args.get('next')
    if next_page:
        redirect(next_page)

    if request.method == 'POST':
        # pprint(request.form)
        # pprint(remember_me)
        u = U.query.filter_by(username=request.form['username']).first()
        if u is None or not u.check_password(request.form['Password']):
            # print('密码错误或用户不存在')
            info = {
                'code': 0,
                'msg': "密码错误或用户不存在",
                'url': ""
            }
            return jsonify(info)
            # return redirect(url_for('login'))
        # 字符串转布尔值
        remember_me = bool(request.form['remember_me'])
        # pprint(type(request.form['remember_me']))
        login_status = login_user(u, remember=remember_me)

        if login_status:
            info = {
                'code': 200,
                'msg': "登录成功",
                'url': url_for('index')
            }
        else:
            info = {
                'code': 0,
                'msg': "登录失败",
                'url': ""
            }

        return jsonify(info)

    return render_template('login.html')


# 退出登录
def logout():
    logout_user()
    return redirect(url_for('login'))


# 注册
def register():
    # 判断是否登录
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    if request.method == 'POST':
        # pprint(request.form)
        # 验证不为空
        if request.form['username'] is None or request.form['password'] is None:
            return jsonify({'code': 0, 'msg': 'password或是username不能为空'})

        user = U()
        check_email = user.query.filter_by(email=request.form['email']).first()
        if check_email:
            return jsonify({'code': 0, 'msg': 'email已存在'})

        # 验证重复用户名
        check_user = user.query.filter_by(username=request.form['username']).first()
        if check_user is None:
            new_user = U(username=request.form['username'], email=request.form['email'])
            new_user.set_password(request.form['password'])
            # pprint(passwords)
            try:
                # with db.session.begin():
                # 执行数据库操作
                db.session.add(new_user)
            except Exception as e:
                # 抛出异常
                db.session.rollback()  # 出现错误时回滚事务
                # pprint(str(e))
                return jsonify({'code': 0, 'msg': '提交失败请联系技术人员'})
            else:
                db.session.commit()
                return jsonify({'code': 200, 'msg': '提交成功', 'url': url_for('login')})
            finally:
                # 无论什么情况都会执行这里
                db.session.close()

        else:
            return jsonify({'code': 0, 'msg': "username已存在"})

    return render_template('register.html', title='registration')


# 用户页面
@login_required
def user(username):
    user_data = U.query.filter_by(username=username).first()
    # pprint(user_data)

    if user_data is None:
        abort(404)

    Tweet_data = user_data.myself_Tweets().all()
    Tweet_sql = user_data.myself_Tweets()

    if request.method == "POST":
        if request.form['status'] == "Follow":
            current_user.follow(user_data)
            db.session.commit()
            return jsonify({'msg': '关注成功'})
        else:
            current_user.unfollow(user_data)
            db.session.commit()
            return jsonify({'msg': '取消关注成功'})

    if user_data.img_path:
        user_data.Storage_path = user_data.img_path[7:]
    else:
        user_data.Storage_path = '/static/img/touxiang.jpg'

    # 分页start
    limit = 10
    page = request.args.get('page', 1, type=int)
    start = (page - 1) * limit
    end = page * limit if len(Tweet_data) > page * limit else len(Tweet_data)
    paginate = Tweet_sql.paginate(page=page, per_page=limit, error_out=False)
    ret = Tweet_sql.slice(start, end)
    # pprint(len(Tweet_data))
    # 分页end

    for index, value in enumerate(ret):
        datas = utils.Capture_image_path(value.body)
        if datas:
            ret[index].cover = datas[0]
        else:
            ret[index].cover = "static/img/jzytp.jpg"

    pprint(ret)

    # pprint(Tweet_data[0].cover)

    return render_template('user.html', user_data=user_data, Tweet_data=ret, paginate=paginate)

# 关注或者粉丝用户列表
@login_required
def user_list():
    return render_template('user_list.html')


# 修改我的资料页面
@login_required
def edit_profile():
    user_data = current_user
    # pprint(user_data)
    if request.method == "POST":
        # pdb.set_trace() # 断点

        # ////////////////为上传文件单开一个区域start//////////////////
        upload_folder = 'twittor/static/upload/img/'

        if 'file' in request.files:
            return utils.upload_img(request.files, upload_folder)
        # ////////////////为上传文件单开一个区域end//////////////////

        # 验证不为空
        if request.form['username'] is None:
            return jsonify({'code': 0, 'msg': 'username不能为空'})


        user = U()
        check_email = user.query.filter(user.id != user_data.id, user.email == request.form['email']).all()
        if check_email:
            return jsonify({'code': 0, 'msg': 'email已存在'})

        # 验证重复用户名
        check_user = user.query.filter(user.id != user_data.id, user.username == request.form['username']).first()
        if check_user is None:
            try:
                new_dict = {'username': request.form['username'], 'email': request.form['email'],
                            'about_me': request.form['about_me']}
                # 判断是否修改了头像
                if request.form['img_name'] is not None and request.form['img_name'] != user_data.img_name:
                    img_path = upload_folder + request.form['img_name']
                    new_dict.update({'img_name': request.form['img_name'], 'img_path': img_path})
                    # # 删除原有的图片
                    if user_data.img_name is not None and user_data.img_name != 'None' and user_data.img_name:
                        utils.delete_file(user_data.img_path)

                if request.form['password']:
                    new_dict['password_hash'] = generate_password_hash(request.form['password'])

                pprint(new_dict)
                user.query.filter_by(id=user_data.id).update(new_dict)

            except Exception as e:
                db.session.rollback()
                pprint(e)
                return jsonify({'code': 0, 'msg': e})
            else:
                db.session.commit()
                return jsonify({'code': 200, 'msg': '修改成功', 'url': url_for('index')})
            finally:
                db.session.close()
        else:
            return jsonify({'code': 0, 'msg': "username已存在"})

    if user_data.img_path:
        user_data.Storage_path = user_data.img_path[7:]
    else:
        user_data.Storage_path = ""
    # pprint(user_data.Storage_path)
    return render_template('edit_profile.html', user_data=user_data)


@login_required
def article_editor():
    if request.method == "POST":
        # pprint(request.form['id'] == '0')
        try:
            if request.form['id'] == '0':
                # 添加
                # pprint('1111111')
                t = T(body=request.form['body'], userid=current_user.id, text_body=request.form['text_body'],
                      create_time=datetime.now(), title=request.form['title'])
                db.session.add(t)
            else:
                # 修改
                # pprint('2222222')
                t = {'body': request.form['body'], 'userid': current_user.id, 'text_body': request.form['text_body'],
                     'create_time': datetime.now(), 'title': request.form['title']}
                T.query.filter_by(id=request.form['id']).update(t)

        except Exception as e:
            db.session.rollback()
            # pprint(e)
            return jsonify({'code': 400, 'msg': '提交失败'})
        else:
            db.session.commit()
            return jsonify({'code': 200, 'msg': '提交成功', 'url': '/user/'+current_user.username})
        finally:
            db.session.close()

    get_id = request.args.get('id', 0)
    data = dir()
    # 保证只能编辑自己的数据
    yourself = False

    if not get_id:
        body = ""
        yourself = True
    else:
        data = T.query.filter_by(id=get_id).first()
        body = data.body
        if data.userid == current_user.id:
            yourself = True

    check_look_or_edit = request.args.get('check_look_or_edit')
    if not check_look_or_edit or (yourself == False):
        data.blog_post()
        is_edit_status = False
    else:
        is_edit_status = True

    # 受欢迎的10条数据
    popular_ten_datas = T.popular_ten_data()

    for key, value in enumerate(popular_ten_datas):
        pprint(popular_ten_datas[key].id)

    return render_template('article_editor.html', id=get_id, body=body, is_edit_status=is_edit_status, data=data,
                           popular_ten_datasss=popular_ten_datas)


def delete_Tweet():
    if request.method == 'POST':

        Tweet_id = request.form['Tweet_id']
        Tweet_del_data = T.query.filter_by(id=Tweet_id).first()

        if Tweet_del_data is not None:
            try:
                path_data = utils.Capture_image_path(Tweet_del_data.body)
                if path_data:
                    for data in path_data:
                        # pprint(data)
                        utils.delete_file('twittor/' + data)

                db.session.delete(Tweet_del_data)
            except Exception as e:
                db.session.rollback()
                return jsonify({'code': 400, 'msg': '删除失败'})
            else:
                db.session.commit()
                return jsonify({'code': 200, 'msg': '删除成功'})
            finally:
                db.session.close()
        else:
            return jsonify({'code': 400, 'msg': '数据错误'})


def forget_password():
    if request.method == 'POST':
        check_email = U.query.filter_by(email=request.form['email']).first()
        if request.form['status'] == '1':
            # 发送验证码
            # 查询是否存在邮箱
            if check_email is None:
                return jsonify({'code': 400, 'msg': '该邮箱没有注册'})

            # 生成一个随机的6位数
            six_digit_number = random.randint(100000, 999999)
            # pprint(six_digit_number)
            # 过期时间为30分钟
            expiration_time = datetime.now() + timedelta(minutes=30)
            # 使用jwt封装加密验证码
            payload = {'user_id': check_email.id, 'vercode': six_digit_number, 'exp': expiration_time}
            utils_data = utils.jwt_Encryption_decryption(1, payload)
            if utils_data['code'] == 200:
                html = "<body style='font-family: Arial, sans-serif;color: #333;'>" \
                       "<div style=' width: 600px;margin: 0 auto;padding: 20px;background-color: #f9f9f9;'>" \
                       "<p>尊敬的用户，</p>" \
                       "<p>您的验证码是：" \
                       "<span style='font-size: 2em;font-weight: bold;color: #1a237e;'>" + str(
                        six_digit_number) + "</span>" \
                        "</p>" \
                        "<p>请在指定时间内使用此验证码完成验证。</p><p>感谢您的使用！</p>" \
                        "</div>" \
                        "</body>"
                send_email = utils.send_email('筠博客账号忘记密码验证', request.form['email'], html)
                send_email.update({'payload': utils_data['payload']})
                # pprint(send_email)
                return jsonify(send_email)
            else:
                return jsonify(utils_data)
            # pprint(utils_data)

        elif request.form['status'] == '2':
            # 提交修改密码的表单
            if check_email.username != request.form['username']:
                return jsonify({'code': 400, 'msg': '昵称与邮箱不对应'})

            data = utils.jwt_Encryption_decryption(2, request.form['check_vercode'])
            # pprint(data)
            if data['code'] == 200:
                datas = data['payload']

                if datas['user_id'] != check_email.id:
                    return jsonify({'code': 400, 'msg': '用户ID错误'})

                if datas['vercode'] != int(request.form['vercode']):
                    return jsonify({'code': 400, 'msg': '验证码错误'})

                check_email.password_hash = generate_password_hash(request.form['password'])
                db.session.commit()

                return jsonify({'code': 200, 'msg': '修改成功'})

            else:
                return jsonify(data)

    return render_template('forget_password.html')


# 为tinymce富文本编辑器定制上传接口
def tinymce_upload_images():
    if request.method == "POST":
        upload_folder = 'twittor/static/upload/tinymce/'
        # pprint('file' in request.files)
        if 'file' in request.files:
            upload_img_data = utils.upload_img(request.files, upload_folder)
            upload_img_data_json = json.loads(upload_img_data.data)
            file_path = upload_img_data_json['file_path'][7:]
            if upload_img_data_json['code'] == '400':
                return jsonify({'location': '', 'status': False})
            else:
                return jsonify({'location': file_path, 'status': True})
        else:
            return jsonify({'location': '', 'status': False})


# 处理异常的页面
def page_not_find(e):
    return render_template('404.html'), 404
